package com.naiterui.ehp.bs.search.config;

import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <pre>
 *
 * </pre>
 *
 * @author 王泽浩
 * @date 2018/9/1 下午2:30
 * @since 1.0.0
 */
@Slf4j
@Configuration
public class EsConfiguration {

    @Bean(initMethod = "init")
    @ConfigurationProperties(prefix = "spring.es")
    public EsProperties esProperties() {
        return new EsProperties();
    }

    @Bean
    public RestHighLevelClient client(EsProperties esProperties) {
        String[] nodes = esProperties.getNodes().split(EsProperties.SPLIT_NODES);
        HttpHost[] httpHosts = Arrays.stream(nodes).map(HttpHost::create).toArray(HttpHost[]::new);
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHosts).setHttpClientConfigCallback(
                requestConfig -> requestConfig.setKeepAliveStrategy((response, context) -> esProperties.getKeepAlive())));
        log.info("初始化 es client nodes: {}", Arrays.toString(httpHosts));
        return client;
    }
}
